//
//  CBTImageTools.m
//  CBT
//
//  Created by Mr.Zhang on 2018/12/20.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "CBTImageTools.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation CBTImageTools

+ (void)saveUserImageWithImage:(UIImage *)image imageName:(NSString *)imageName userID:(NSString *)userID
{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    NSString* savePath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@_%@",userID,[self md5:imageName]]];
    
    [fileManager changeCurrentDirectoryPath:savePath];

    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    
    if ([fileManager fileExistsAtPath:savePath]) {
        NSLog(@"用户图片 文件 已存在");
        return;
    }else{
        
        //删除旧头像
        NSArray *oldFileList = [fileManager contentsOfDirectoryAtPath:path error:nil];
        for (NSString *file in oldFileList) {
            NSString *usersID = [[file componentsSeparatedByString:@"_"]objectAtIndex:0];
            if ([usersID isEqualToString:[NSString stringWithFormat:@"%@",userID]]) {
                [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",path,file] error:nil];
            }
        }
        //保存新头像
        [fileManager createFileAtPath:savePath contents:UIImageJPEGRepresentation(image, 0.5) attributes:nil];
    }
}

+ (NSString *)getUserImageNameWithUserID:(NSString *)ID
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    for (NSString *file in fileList) {
        NSString *userID = [[file componentsSeparatedByString:@"_"]objectAtIndex:0];
        if ([userID isEqualToString:[NSString stringWithFormat:@"%@",ID]]) {
            return  [NSString stringWithFormat:@"%@/%@",path,file];
        }
    }
    return @"-1";
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end
